# coding=utf-8
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.response import Response
from rest_framework.views import APIView

from comment.response_content import OBJECT_DOES_NOT_EXIST, DELETE_COMMENT_SUCCESSFUL, AUTHENTICATE_ERROR, \
    UPDATE_COMMENT_SUCCESSFUL, COMMENT_DOES_NOT_EXIST
from utils.decorators import need_login, operation_log
from utils.shortcuts import get_class_content
from utils.shortcuts import http_400_response, paginate
from .models import Comment
from .serializers import CommentDetailSer
from .serializers import CommentSer, CommentUpdateSer


# Create your views here.
class CommentView(APIView):
    """ 回复"""

    def get(self, request, **kwargs):
        comments = Comment.objects.all()
        if request.GET.get("source", None):
            comments = comments.filter(source=request.GET['source'])
        if request.GET.get("object_id", None):
            comments = comments.filter(object_id=request.GET['object_id'])
        if request.GET.get("comments_to_me", None):
            comments = comments.filter(comment_to_user=request.user)
        if request.GET.get("current_time", None):
            comments = comments.filter(created_time__lt=request.GET["current_time"])
        return paginate(request, comments, CommentDetailSer)

    @need_login
    @operation_log('create comment')
    def post(self, request, **kwargs):
        data = request.data.copy()
        data["creater"] = request.user.id
        try:
            get_class_content(data["source"], data["object_id"])
        except ObjectDoesNotExist:
            return Response({"status": OBJECT_DOES_NOT_EXIST})
        if data.get("comment_to", None):
            comment = Comment.objects.get(pk=data["comment_to"])
            if data['creater'] != comment.creater.id:  # 如果请求的userid和数据库里的createrid不同
                data["comment_to_user"] = comment.creater.id
            else:
                data["comment_to_user"] = None
        elif data["source"] in ["found"]:
            data["comment_to_user"] = None
        ser = CommentSer(data=data)
        if ser.is_valid():
            comment = ser.save()
        else:
            return http_400_response(ser.errors)
        return Response(CommentDetailSer(comment).data, status=201)


class CommentObjectView(APIView):
    @need_login
    @operation_log('delete comment')
    def delete(self, request, **kwargs):
        try:
            comment = Comment.objects.get(uuid=kwargs["uuid"])
        except ObjectDoesNotExist:
            return http_400_response(COMMENT_DOES_NOT_EXIST)
        if (not request.user.is_superuser) and (comment.creater.id != request.user.id):
            return http_400_response({"status": AUTHENTICATE_ERROR})
        # 将所有对此条评论进行回复的评论comment_to属性置None
        Comment.objects.filter(comment_to=comment).update(comment_to=None)
        comment.delete()
        return Response({"status": DELETE_COMMENT_SUCCESSFUL})

    @need_login
    @operation_log('modify comment')
    def put(self, request, **kwargs):
        try:
            comment = Comment.objects.get(uuid=kwargs["uuid"])
        except ObjectDoesNotExist:
            return http_400_response(COMMENT_DOES_NOT_EXIST)
        if request.data.get("is_readed", None):
            if comment.comment_to_user.id == request.user.id:
                comment.is_readed = True
                comment.save()

        if (not request.user.is_superuser) and (comment.creater.id != request.user.id):
            return http_400_response({"status": AUTHENTICATE_ERROR})
        ser = CommentUpdateSer(comment, data=request.data, partial=True)
        if ser.is_valid():
            ser.save()
        else:
            return http_400_response(ser.errors)
        return Response({"status": UPDATE_COMMENT_SUCCESSFUL})
